package com.liu.concurrent.sync;

import java.util.concurrent.locks.ReentrantLock;

public class Account implements Runnable {
    private final ReentrantLock lock=new ReentrantLock();
    private String accountNo;
    private double balance;
    public Account(String accountNo,double balance){
        this.accountNo=accountNo;
        this.balance=balance;
    }
 
    //因为账户余额不可以随便更改，所以只为balance提供getter方法
    public double getBalance() {
        return balance;
    }
 
    public String getAccountNo() {
        return accountNo;
    }
 
    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
 
        Account account = (Account) o;
 
        return accountNo.equals(account.accountNo);
 
    }
 
    @Override
    public int hashCode() {
        return accountNo.hashCode();
    }
 
    //提供一个线程安全的draw()方法来完成取钱操作
    public void draw(double drawAmount){
        //加锁
        lock.lock();
        try {
            if (balance >= drawAmount) {
                System.out.println(Thread.currentThread().getName() + "取钱成功！吐出钞票：" + drawAmount);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                balance -= drawAmount;
                System.out.println("\t余额为：" + balance);
            } else {
                System.out.println(Thread.currentThread().getName() + "取钱失败，余额不足");
            }
        }finally {
            lock.unlock();
        }
    }

	public void run() {
		// TODO Auto-generated method stub
		draw(500);
	}
	public static void main(String[] args) {
		Account syncTest1 = new Account("刘波",1000);
		Account syncTest2 = new Account("张三",1000);
		Thread thread1 = new Thread(syncTest1);
		Thread thread2 = new Thread(syncTest2);
		thread1.start();
		thread2.start();
	}
}
